<template>
  <div class="exam-container">
    <!-- 页面标题 -->
    <div class="exam-header">
      <h1>{{ route.query.name }}</h1>
      <p class="question-count">共 {{ examList.length }} 题 | 已完成 {{ completedCount }} 题</p>
    </div>

    <!-- 题目列表 -->
    <div class="question-list" v-if="examList.length > 0">
      <div 
        class="question-item" 
        v-for="(question, index) in examList" 
        :key="question.id || index"
      >
        <!-- 题目序号、题型和分值 -->
        <div class="question-header">
          <span class="question-index">{{ index + 1 }}. </span>
          <span class="question-type">
            {{ getTypeName(question.type) }} ({{ question.score }}分)
          </span>
        </div>

        <!-- 题目内容 -->
        <div class="question-content">
          {{ question.content }}
        </div>

        <!-- 选项列表：根据题型切换 -->
        <div class="options">
          <!-- 单选题 (type=1) -->
          <div v-if="question.type === 1" class="option-group">
            <label 
              class="option-item"
              v-for="(option, optIndex) in question.questionOptionList" 
              :key="option.id"
            >
              <input 
                type="radio" 
                :name="`question-${question.id}`" 
                :value="option.id"
                v-model="userAnswers[index]"
                class="option-radio"
              >
              <span class="option-letter">{{ String.fromCharCode(65 + optIndex) }}.</span>
              <span class="option-text">{{ option.optionContent }}</span>
            </label>
          </div>

          <!-- 多选题 (type=2) -->
          <div v-if="question.type === 2" class="option-group">
            <label 
              class="option-item"
              v-for="(option, optIndex) in question.questionOptionList" 
              :key="option.id"
            >
              <input 
                type="checkbox" 
                :value="option.id"
                v-model="userAnswers[index]"
                class="option-checkbox"
              >
              <span class="option-letter">{{ String.fromCharCode(65 + optIndex) }}.</span>
              <span class="option-text">{{ option.optionContent }}</span>
            </label>
          </div>

          <!-- 判断题 (type=3) -->
          <div v-if="question.type === 3" class="option-group judge-options">
            <label 
              class="option-item"
              v-for="(option, optIndex) in question.questionOptionList" 
              :key="option.id"
            >
              <input 
                type="radio" 
                :name="`question-${question.id}`" 
                :value="option.id"
                v-model="userAnswers[index]"
                class="option-radio"
              >
              <span class="option-text">{{ option.optionContent }}</span>
            </label>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div class="loading" v-else>
      加载题目中...
    </div>

    <!-- 提交按钮 -->
    <div class="submit-area" v-if="examList.length > 0">
      <button 
        class="submit-btn"
        @click="handleSubmit"
        :disabled="hasUnanswered || submitting"
      >
        <span v-if="!submitting">提交答案</span>
        <span v-if="submitting">提交中...</span>
      </button>
      <p class="warning-text" v-if="hasUnanswered">
        ⚠️ 还有未完成的题目
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getPaperQuestion, examAdd, selectAnswer  } from "@/api/common"

// 响应式数据
const examList = ref([]);
const userAnswers = ref([]); // 存储用户答案：单选/判断存字符串，多选存数组
const submitting = ref(false); // 提交状态
const route = useRoute();
const router = useRouter();
const toast = inject("toast")

// 计算属性：已完成题目数量
const completedCount = computed(() => {
  return examList.value.filter((question, index) => {
    const answer = userAnswers.value[index];
    if (question.type === 1 || question.type === 3) {
      // 单选/判断：有值即为完成
      return answer !== undefined && answer !== null;
    } else if (question.type === 2) {
      // 多选：数组长度>0即为完成
      return Array.isArray(answer) && answer.length > 0;
    }
    return false;
  }).length;
});

// 计算属性：判断是否有未回答的题目
const hasUnanswered = computed(() => {
  return examList.value.some((question, index) => {
    const answer = userAnswers.value[index];
    if (question.type === 1 || question.type === 3) {
      // 单选/判断：未选择
      return answer === undefined || answer === null;
    } else if (question.type === 2) {
      // 多选：未选择任何选项
      return !Array.isArray(answer) || answer.length === 0;
    }
    return true;
  });
});

// 题型名称映射
const getTypeName = (type) => {
  const typeMap = {
    1: '单选题',
    2: '多选题',
    3: '判断题'
  };
  return typeMap[type] || '未知题型';
};

// 初始化
onMounted(() => {
    selectAnswer ({pageNo:1,pageSize:10}).then(res => {})
  getPaperQuestion({ id: route.query.id }).then(res => {
    if (res.data && res.data.length) {
      examList.value = res.data;
      // 初始化答案数组（单选/判断为null，多选为空数组）
      userAnswers.value = res.data.map(question => {
        return question.type === 2 ? [] : null;
      });
    } else {
      toast.msg('未获取到题目数据');
    }
  }).catch(err => {
    console.error('获取题目失败', err);
    toast.msg(err.message);
  });
});

// 提交答案处理
const handleSubmit = () => {
  if (hasUnanswered.value) return;

  submitting.value = true;

  // 格式化提交数据（按要求的格式构造）
  const submitData = {
    planId: route.query.id, // 从路由参数获取planId
    paperId: Number(route.query.paperId), // 试卷ID（从路由参数获取）
    questionOptionList: userAnswers.value.map((answer, index) => {
      const question = examList.value[index];
      return {
        questionId: question.id, // 题目ID
        // 选项ID：多选以逗号分隔字符串，单选/判断直接传字符串
        optionId: question.type === 2 
          ? answer.join(',') 
          : String(answer)
      };
    })
  };

  // 调用提交接口
  examAdd(submitData).then(res => {
    toast.msg('提交成功！');
    // 提交成功后跳转到结果页
    router.push({
      path: '/test'
    });
  }).catch(err => {
    console.error('提交失败', err);
    toast.msg(err.message);
    submitting.value = false; // 恢复提交状态
  });
};
</script>

<style scoped lang="less">
/* 样式保持不变，与上一版一致 */
.exam-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.exam-header {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
  
  h1 {
    margin: 0;
    color: #333;
    font-size: 24px;
  }
  
  .question-count {
    color: #666;
    margin: 8px 0 0;
    font-size: 14px;
  }
}

.question-list {
  margin-bottom: 40px;
}

.question-item {
  margin-bottom: 25px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  
  &:last-child {
    margin-bottom: 0;
  }
}

.question-header {
  margin-bottom: 12px;
  font-size: 14px;
  
  .question-index {
    font-weight: bold;
    color: #1890ff;
  }
  
  .question-type {
    color: #888;
    font-style: italic;
  }
}

.question-content {
  margin-bottom: 18px;
  font-size: 16px;
  color: #333;
  line-height: 1.5;
}

.options {
  padding-left: 10px;
}

.option-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.judge-options {
  flex-direction: row;
  gap: 30px;
  margin-top: 10px;
}

.option-item {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 10px;
  border-radius: 4px;
  transition: background-color 0.2s;
  
  &:hover {
    background-color: #f0f7ff;
  }
}

.option-radio, .option-checkbox {
  margin-right: 12px;
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.option-letter {
  font-weight: 500;
  color: #1890ff;
  margin-right: 8px;
  width: 20px;
}

.option-text {
  color: #666;
  font-size: 15px;
}

.submit-area {
  text-align: center;
  padding: 20px 0;
  position: sticky;
  bottom: 0;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
  margin-top: 20px;
  
  .submit-btn {
    padding: 12px 40px;
    background: #1890ff;
    color: #fff;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    transition: background 0.3s;
    
    &:hover {
      background: #096dd9;
    }
    
    &:disabled {
      background: #ccc;
      cursor: not-allowed;
      opacity: 0.7;
    }
  }
  
  .warning-text {
    margin: 10px 0 0;
    color: #faad14;
    font-size: 14px;
  }
}

.loading {
  text-align: center;
  padding: 80px 0;
  color: #666;
  font-size: 16px;
}
</style>